/*
 * @lc app=leetcode.cn id=208 lang=cpp
 *
 * [208] 实现 Trie (前缀树)
 */

// @lc code=start
#include <bits/stdc++.h>
using namespace std;

struct Node
{
    int end = 0;//表示到此为止的单词一共有多少个
    Node* next[26];//26个英文字母
    Node()
    {
        end = 0;
        memset(next, 0, sizeof(next));
    };
    ~Node()
    {
        for(auto n : next)
        {
            delete n;
        }
    }
};


class Trie {

    Node* root;
public:
    Trie() {
        root = new Node;
    }
    ~Trie()
    {
        delete root;
    }

    void insert(string word) {
        Node* node = root;
        int i = 0;
        for(; i < word.length() - 1; i ++)
        {
            auto ch = word[i];
            if(NULL == node->next[ch - 'a'])
            {
                node->next[ch - 'a'] = new Node;
            }
            node = node->next[ch - 'a'];
        }

        auto ch = word[i];
        if(NULL == node->next[ch - 'a'])
        {
            node->next[ch - 'a'] = new Node;
        }
        node->next[ch - 'a']->end ++;
    }
    
    bool search(string word) {
        Node* node = this->startsWith2(word);
        if(node && node->end)
        {
            return true;
        }
        return false;
    }
    
    bool startsWith(string prefix) {
        return this->startsWith2(prefix);
    }

private:
    Node* startsWith2(const string& prefix)
    {
        Node* node = root;
        int i = 0;
        for(; i < prefix.length() - 1; ++i)
        {
            auto ch = prefix[i];
            if(NULL == node->next[ch - 'a'])
            {
                return NULL;
            }
            node = node->next[ch - 'a'];
        }
        
        auto ch = prefix[i];
        node = node->next[ch - 'a'];
        return node;
    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */
// @lc code=end

